package org.jeecg.modules.articles.service.impl;

import org.jeecg.modules.articles.entity.BlogArticles;
import org.jeecg.modules.articles.mapper.BlogArticlesMapper;
import org.jeecg.modules.articles.service.BlogArticlesService;
import org.jeecg.modules.categories.entity.BlogCategories;
import org.jeecg.modules.categories.mapper.BlogCategoriesMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;

/**
 * @Description: blog_articles
 * @Author: jeecg-boot
 * @Date:   2025-06-30
 * @Version: V1.0
 */
@Service
public class BlogArticlesServiceImpl extends ServiceImpl<BlogArticlesMapper, BlogArticles> implements BlogArticlesService {

    @Resource
    private BlogCategoriesMapper blogCategoriesMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(BlogArticles entity) {
        // 根据categoryId自动填充categoryName
        if (entity.getCategoryId() != null) {
            BlogCategories category = blogCategoriesMapper.selectById(entity.getCategoryId());
            if (category != null) {
                entity.setCategoryName(category.getName());
            }
        }
        
        boolean result = super.save(entity);
        
        // 如果文章状态为发布状态，更新分类文章数量
        if (result && entity.getStatus() != null && entity.getStatus() == 1 && entity.getCategoryId() != null) {
            blogCategoriesMapper.updateArticleCount(entity.getCategoryId(), 1);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(BlogArticles entity) {
        // 获取更新前的文章信息
        BlogArticles oldArticle = this.getById(entity.getId());
        
        // 根据categoryId自动填充categoryName
        if (entity.getCategoryId() != null) {
            BlogCategories category = blogCategoriesMapper.selectById(entity.getCategoryId());
            if (category != null) {
                entity.setCategoryName(category.getName());
            }
        }
        
        boolean result = super.updateById(entity);
        
        if (result && oldArticle != null) {
            // 处理分类变化
            if (!Objects.equals(oldArticle.getCategoryId(), entity.getCategoryId())) {
                // 分类发生变化，需要更新两个分类的文章数量
                if (oldArticle.getStatus() != null && oldArticle.getStatus() == 1) {
                    blogCategoriesMapper.updateArticleCount(oldArticle.getCategoryId(), -1);
                }
                if (entity.getStatus() != null && entity.getStatus() == 1 && entity.getCategoryId() != null) {
                    blogCategoriesMapper.updateArticleCount(entity.getCategoryId(), 1);
                }
            } else {
                // 分类未变化，只处理状态变化
                handleStatusChange(oldArticle, entity);
            }
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        // 获取删除前的文章信息
        BlogArticles article = this.getById(id);
        
        // 执行逻辑删除（设置del_flag=1）
        boolean result = super.removeById(id);
        
        // 如果删除的是已发布的文章，更新分类文章数量
        if (result && article != null && article.getStatus() != null && article.getStatus() == 1 && article.getCategoryId() != null) {
            blogCategoriesMapper.updateArticleCount(article.getCategoryId(), -1);
        }
        
        return result;
    }

    /**
     * 处理文章状态变化
     * @param oldArticle 更新前的文章
     * @param newArticle 更新后的文章
     */
    private void handleStatusChange(BlogArticles oldArticle, BlogArticles newArticle) {
        Integer oldStatus = oldArticle.getStatus();
        Integer newStatus = newArticle.getStatus();
        
        if (oldStatus == null || newStatus == null || newArticle.getCategoryId() == null) {
            return;
        }
        
        // 从草稿/下架变为发布：+1
        if (oldStatus != 1 && newStatus == 1) {
            blogCategoriesMapper.updateArticleCount(newArticle.getCategoryId(), 1);
        }
        // 从发布变为草稿/下架：-1
        else if (oldStatus == 1 && newStatus != 1) {
            blogCategoriesMapper.updateArticleCount(newArticle.getCategoryId(), -1);
        }
    }

    @Override
    public int countPublishedArticlesByCategory(String categoryId) {
        QueryWrapper<BlogArticles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId)
                   .eq("status", 1) // 1表示已发布状态
                   .eq("del_flag", 0); // 未删除
        return (int) this.count(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recalculateCategoryArticleCount(String categoryId) {
        QueryWrapper<BlogArticles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId)
                   .eq("status", 1) // 1表示已发布状态
                   .eq("del_flag", 0); // 未删除
        int count = (int) this.count(queryWrapper);
        blogCategoriesMapper.setArticleCount(categoryId, count);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recalculateAllCategoryArticleCounts() {
        List<String> categoryIds = blogCategoriesMapper.selectAllCategoryIds();
        for (String categoryId : categoryIds) {
            recalculateCategoryArticleCount(categoryId);
        }
    }
}
